package com.example.inventoryservice.controller;

import com.example.inventoryservice.bean.Inventory;
import com.example.inventoryservice.service.InventoryService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/inventory")
public class InventoryController {
    @Autowired
    private InventoryService service;

    @HystrixCommand(fallbackMethod = "findByProductIdFallback")
    @RequestMapping("/findbyproductid/{productId}")
    public Inventory findByProductId(@PathVariable Long productId) throws Exception {
        Inventory inventory = service.findByProductId(productId);
        if (inventory == null) throw new Exception("Inventory not found");
        return inventory;
    }

    @HystrixCommand(fallbackMethod = "lockStockFallback")
    @RequestMapping(value = "/lock/{productId}/{quantity}", method = RequestMethod.POST)
    public boolean lockStock(@PathVariable Long productId, @PathVariable Integer quantity) throws Exception {
        boolean result = service.lockStock(productId, quantity);
        if (!result) throw new Exception("Failed to lock stock");
        return true;
    }

    @HystrixCommand(fallbackMethod = "releaseStockFallback")
    @RequestMapping(value = "/release/{productId}/{quantity}", method = RequestMethod.POST)
    public boolean releaseStock(@PathVariable Long productId, @PathVariable Integer quantity) throws Exception {
        boolean result = service.releaseStock(productId, quantity);
        if (!result) throw new Exception("Failed to release stock");
        return true;
    }

    @HystrixCommand(fallbackMethod = "deductStockFallback")
    @RequestMapping(value = "/deduct/{productId}/{quantity}", method = RequestMethod.POST)
    public boolean deductStock(@PathVariable Long productId, @PathVariable Integer quantity) throws Exception {
        boolean result = service.deductStock(productId, quantity);
        if (!result) throw new Exception("Failed to deduct stock");
        return true;
    }

    public Inventory findByProductIdFallback(Long productId) {
        Inventory inventory = new Inventory();
        inventory.setId(-1L);
        inventory.setProductId(productId);
        inventory.setTotalStock(0);
        inventory.setLockedStock(0);
        inventory.setAvailableStock(0);
        return inventory;
    }

    public boolean lockStockFallback(Long productId, Integer quantity) { return false; }
    public boolean releaseStockFallback(Long productId, Integer quantity) { return false; }
    public boolean deductStockFallback(Long productId, Integer quantity) { return false; }
}